/*
 * @Date: 2023-03-12 21:43:26
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:
 * @LastEditTime: 2023-03-12 22:11:46
 * @FilePath: \server\system\service\login\login.go
 */
package login

import (
	"chunDoc/system/service/configService"
	"chunDoc/system/util/jwtUtil"
	"errors"
)

type LoginService struct{}

type ResultUser struct {
	Username string `json:"username"`
	Level    int64  `json:"level"`
	Token    string `json:"token"`
}

//返回级别，0表示登陆失败，2表示普通用户，1表示管理员
func (_this *LoginService) Login(username string, password string) (err error, re ResultUser) {
	var configSer configService.ConfigService
	users := configSer.GetUsers()
	for _, user := range users {
		if user.Login == username && user.Password == password {
			if user.IsAdmin == 1 {
				re.Level = 1
			} else {
				re.Level = 2
			}
			re.Username = username
			//创建token
			s := jwtUtil.NewJWT()
			clams := s.CreateClaims(jwtUtil.BaseClaims{
				UserName: username,
				Level:    re.Level,
			})
			tokens, err := s.CreateToken(clams)
			if err != nil {
				return err, re
			}

			re.Token = tokens
			return nil, re
		}
	}
	return errors.New("用户名密码错误"), re
}
